package com.example.controller;

import com.example.config.redis.RedisService;
import com.example.entity.Permission;
import com.example.entity.User;
import com.example.entity.UserInfo;
import com.example.utils.JwtUtils;
import com.example.utils.MenuTree;
import com.example.utils.Result;
import com.example.vo.RouterVo;
import com.example.vo.TokenVo;
import io.jsonwebtoken.Jwts;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/sysUser")
public class SysUserController {
    @Resource
    private RedisService redisService;
    @Resource
    private JwtUtils jwtUtils;

    /**
     * 刷新token
     * @param request
     * @return
     */
    @PostMapping("/refreshToken")
    public Result refreshToken(HttpServletRequest request){
        //从header中获取前端提交的token
        String token = request.getHeader("token");
        //如果请求头中没有token，那么就从参数中获取
        if (ObjectUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        //从springSecurity上下文中获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //获取身份信息
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        //重新生成token
        String newToken = "";
        //验证原来的token是否合法
        if (jwtUtils.validateToken(token,userDetails)){
            newToken = jwtUtils.refreshToken(token);
        }
        //获取本次token的到期时间，交给前端做判断
        long expireTime = Jwts.parser().setSigningKey(jwtUtils.getSecret())
                .parseClaimsJws(newToken.replace("jwt_", ""))
                .getBody().getExpiration().getTime();
        //清除原来的token信息
        redisService.del("token_" + token);
        //存储新的token信息
        redisService.set("token_" + newToken, newToken, jwtUtils.getExpiration()/1000);
        return Result.ok(new TokenVo(newToken, expireTime)).message("token刷新成功");
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getInfo")
    public Result getInfo(){
        //从Spring Security上下文获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //判断authentication对象是否为空
        if (ObjectUtils.isEmpty(authentication)){
            return Result.error().message("用户信息获取失败");
        }
        //获取用户信息
        User user = (User) authentication.getPrincipal();
        //用户权限集合
        List<Permission> permissionList = user.getPermissionList();
        //获取角色权限编码字段
        Object[] roles = permissionList.stream().filter(Objects::nonNull)
                .map(Permission::getCode).toArray();
        //创建用户信息对象
        UserInfo userInfo = new UserInfo(user.getId(), user.getUsername(), user.getAvatar(), null, roles);
        return Result.ok(userInfo).message("用户信息获取成功");
    }

    /**
     * 获取用户菜单数据
     * @return
     */
    @GetMapping("/getMenuList")
    public Result getMenuList(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        List<Permission> permissionList = user.getPermissionList();
        //筛选当前用户所拥有的目录和菜单数据
        List<Permission> collect = permissionList.stream()
                //0-菜单 1-目录 2-按钮
                .filter(item->item!=null && item.getType()!=2)
                .collect(Collectors.toList());
        //生成路由数据
        List<RouterVo> routerList = MenuTree.makeRouter(collect, 0L);
        return Result.ok(routerList).message("菜单数据获取成功");
    }

    /**
     * 用户退出登录
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request, HttpServletResponse response){
        //获取token信息
        String token = request.getHeader("token");
        if (ObjectUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        //从springSecurity上下文中获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //判断用户信息是否为空，如果不为空，则需要清空用户
        if (authentication!=null){
            new SecurityContextLogoutHandler().logout(request, response, authentication);
            redisService.del("token_" + token);
            return Result.ok().message("用户退出成功!");
        }
        return Result.error().message("用户退出失败!");
    }
}
